<script setup>
import { ref, reactive, onMounted } from 'vue';
import { speciesPage, saveSpecies, delSpecies } from '@/utils/api';
import { ElMessage, ElMessageBox } from 'element-plus';
const pageNum = ref(1);
const currentPage = ref(1);
const totalElements = ref(0);
const list = ref([]);
let areaId = '';

let speFile = '';
let speid = null;
let isspe = true;
const issp = ref(false);
const imageUrl = ref('');
const ruleFormRef = ref(null);
const ruleForm = ref({
    speciesName: '',
    content: ''
})

const rule = reactive({
    speciesName: [
        { required: true, message: '请输入物种名称', trigger: 'blur' }
    ],
    content: [
        { required: true, message: '请输入物种介绍', trigger: 'blur' }
    ]
})

const handleAvatar = (files) => {
    const file = files.raw;
    // const isJPG = (file.type === 'image/jpeg' || file.type === 'image/png');
    const isLt2M = file.size / 1024 / 1024 < 2;
    // if (!isJPG) {
    //     ElMessage({
    //         message: '只接受jpeg类型图片!',
    //         type: 'warning',
    //     })
    //     return false
    // }
    if (!isLt2M) {
        ElMessage({
            message: '上传图片大小不能超过 2MB!',
            type: 'warning',
        })
        return false
    }
    // return isJPG && isLt2M;

    imageUrl.value = URL.createObjectURL(file);
    speFile = file
};

const delItem = function (data) {
    ElMessageBox.confirm(
        '是否要永久删除该数据. 继续?',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            delSpecies(data.id).then(res => {
                if (res.code == '200') {
                    resetData();
                    ElMessage({
                        type: 'success',
                        message: '删除成功',
                    })
                } else {
                    ElMessage({
                        type: 'warning',
                        message: res.message,
                    })
                }
            })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '已取消',
            })
        })
};


const submitForm = async (formEl) => {
    if (!formEl) return
    if (imageUrl.value == '') {
        ElMessage({
            message: '请选择封面图',
            type: 'warning',
        })
        return
    }
    await formEl.validate((valid, fields) => {
        if (valid) {
            const pm = ruleForm.value;
            const formData = new FormData();
            if (isspe) {
                let params = {
                    "areaId": areaId,
                    "speciesName": pm.speciesName,
                    "type": 0,
                    "content": pm.content
                }
                formData.append('dataStr', JSON.stringify(params));
                formData.append('file', speFile);
            } else {
                let params = {
                    "id": speid,
                    "areaId": areaId,
                    "speciesName": pm.speciesName,
                    "type": 0,
                    "content": pm.content
                }
                formData.append('dataStr', JSON.stringify(params));
                formData.append('file', speFile);
            }
            saveSpecies(formData).then(res => {
                if (res.code == '200') {
                    ElMessage({
                        message: '操作成功',
                        type: 'success',
                    })
                    resetData();
                    issp.value = false;
                } else {
                    ElMessage({
                        message: res.message,
                        type: 'warning',
                    })
                }
            })
        } else {
            console.log('error submit!', fields)
        }
    })
}

const resetForm = (formEl) => {
    if (!formEl) return
    formEl.resetFields();
    speFile = '';
    imageUrl.value = '';
    issp.value = false;
}


const getspeciesPage = async () => {
    let params = {
        areaId: areaId,
        pageNum: pageNum.value,
        pageSize: 10
    }
    let res = await speciesPage(params)
    if (res.code == '200') {
        list.value = res.data.content;
        totalElements.value = res.data.totalElements;
    }
}

const handleSizeChange = (val) => {
    pageNum.value = val;
    getspeciesPage();
};

const resetData = () => {
    speFile = '';
    imageUrl.value = '';
    pageNum.value = 1;
    currentPage.value = 1;
    getspeciesPage();
}

const addspe = () => {
    ruleForm.value.speciesName = '';
    ruleForm.value.content = '';
    speFile = '';
    imageUrl.value = '';
    isspe = true;
    issp.value = true;
}

const compliespe = (data) => {
    ruleForm.value.speciesName = data.speciesName;
    ruleForm.value.content = data.content;
    speFile = '';
    speid = data.id;
    imageUrl.value = '/api' + data.imgUrl;
    isspe = false;
    issp.value = true;
}


onMounted(() => {
    areaId = window.sessionStorage.getItem('areaId');
    getspeciesPage();
})

</script>
<template>
    <div class="wls-aut">
        <div class="wls-aut-title">
            <div style="font-weight: 700;"><span>物种库 </span></div>
        </div>
        <div class="wls-aut-container" style="padding: .24rem;">
            <el-row>
                <el-col :span="24" style="text-align: right;">
                    <el-button type="primary" @click.stop="addspe">添加物种</el-button>
                </el-col>
            </el-row>
            <div style="height: .16rem;"></div>
            <table>
                <thead>
                    <th>物种封面照片</th>
                    <th>物种名称</th>
                    <th>操作</th> 
                </thead>
                <tbody>
                    <tr v-for="(i, x) in list" :key="x">
                        <td style="display: flex;align-items: center;justify-content: center;padding: .1rem;">
                            <img class="speImg" :src="'/api' + i.imgUrl" alt="">
                        </td>
                        <td>{{ i.speciesName }}</td>
                        <td>
                            <span style="margin:0 .1rem;color: #387BFF;" @click.stop="compliespe(i)">修改</span>
                            <span style="color: #F84848;" class="red" @click.stop="delItem(i)">删除</span>
                        </td>
                    </tr>
                </tbody>
            </table>

            <el-pagination v-model:current-page="currentPage" :page-size="10" :pager-count="5" :small="true"
                :disabled="false" background layout="total, prev, pager, next, jumper" :total="totalElements"
                @current-change="handleSizeChange" />
        </div>

        <div class="hsq-popup" v-if="issp">
            <div class="rule-form">
                <div class="hsq-popup-title">
                    <div class="hsq-popup-shu "></div>
                    <span>添加物种</span>
                </div>

                <div style="height: .16rem;"></div>

                <el-form ref="ruleFormRef" :model="ruleForm" :rules="rule" class="demo-ruleForm" label-position="top"
                    size="large" status-icon>
                    <div style="font-weight: 700;">物种封面图</div>
                    <div style="color: rgb(238, 190, 119);line-height: .5rem;">上传图片大小不能超过 2MB!</div>
                    <el-upload class="avatar-uploader" :auto-upload="false" accept="image/*" :show-file-list="false"
                        :on-change="handleAvatar">
                        <img v-if="imageUrl != ''" :src="imageUrl" class="avatar">
                        <el-icon style="width: 178px;height: 178px;" v-else class="el-icon-plus avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                    <div style="height: 0.16rem;"></div>
                    <el-form-item label="物种名称" prop="speciesName">
                        <el-input v-model="ruleForm.speciesName" placeholder="请输入物种名称" />
                    </el-form-item>
                    <el-form-item label="物种介绍" prop="content">
                        <el-input v-model="ruleForm.content" type="textarea" placeholder="请输入物种介绍" />
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="submitForm(ruleFormRef)">
                            确定
                        </el-button>
                        <el-button @click="resetForm(ruleFormRef)">取消</el-button>
                    </el-form-item>
                </el-form>

            </div>
        </div>

    </div>
</template>
<style scoped>
.speImg {
    display: inline-block;
    width: .6rem;
    height: .4rem;
}

.rule-form {
    width: 6rem;
    padding: 0.24rem;
    border-radius: 4px;
    background-color: #fff;
    overflow: hidden;
}
</style>
